package com.example.demo.common.domain;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class UserClassmateJoinExample {
    public static void main(String[] args) {
        // 数据库连接信息，需根据实际情况修改
        String url = "jdbc:mysql://localhost:3308/db_book";
        String username = "root";
        String password = "123456";

        try {
            // 加载数据库驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 建立数据库连接
            Connection connection = DriverManager.getConnection(url, username, password);
            // 创建 Statement 对象
            Statement statement = connection.createStatement();
            // 编写关联查询的 SQL 语句
            String sql = "SELECT classmate.xuehao, classmate.dorm, user.name, user.age " +
                    "FROM user " +
                    "INNER JOIN classmate " +
                    "ON user.id = classmate.id;";
            // 执行 SQL 查询
            ResultSet resultSet = statement.executeQuery(sql);
            // 处理查询结果
            while (resultSet.next()) {
                int xuehao = resultSet.getInt("xuehao");
                int dorm = resultSet.getInt("dorm");
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                System.out.println("学号: " + xuehao + ", 宿舍号: " + dorm + ", 姓名: " + name + ", 年龄: " + age);
            }
            // 关闭资源
            resultSet.close();
            statement.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}